/*
 * @Author: your name
 * @Date: 2020-04-23 21:08:39
 * @LastEditTime: 2020-05-02 18:45:11
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \my-admin\src\config\axios.js
 */

import axios from 'axios'
import {baseURL,timeout,headers} from './env'
import {getToken} from './auth'

// eslint-disable-next-line no-unused-vars
export default function $axios(options){
    return new Promise((resolve,reject) => {
      let instance = axios.create({
        baseURL,
        headers,
        timeout,
      }) 
  
      /**
       * 请求拦截器
       * 每次请求前，如果存在token则在请求投中携带token
       */
      instance.interceptors.request.use(
          config => {
            /**
            * 即使token存在，也有可能token是过期的，所以在每次请求投中携带token
            * 后台根据携带的token判断用户是否登陆， 并返回相应的状态码
            * 根据返回的状态码，进行统一操作
            */
            let token = getToken('Token')
            if(token){
              config.headers.token = token
            }
            return config
          },
          //请求错误时候
          error => {
            return Promise.reject(error)
          }
      )
      //响应拦截器
      instance.interceptors.response.use(
        response => {
          return response
        },
        error => {
          if(error && error.response){
            switch(error.response.status){
              case 400:
                error.message = '请求错误'
                break
              case 401:
                error.message = '未授权，请登录'
                break
              case 403:
                error.message = '拒绝访问'
                break
              case 404:
                error.message = `请求地址错误：${error.response.config.url}`
                break
              case 408:
                error.message = '请求超时'
                break
              case 500:
                error.message = '服务器内部出错'
                break
              case 501:
                error.message = '服务器未实现'
                break
              case 502:
                error.message = '网关错误'
                break
              case 503:
                error.message = '服务器不可用'
                break
              case 504:
                error.message = '网关超时'
                break
              case 505:
                error.message = 'HTTP版本不受支持'
                break
              default:
            }
          }
          return Promise.reject(error)
        }
      )
      //处理请求
      instance(options).then(response => {
        resolve(response.data)
      }).catch(err => {
        reject(err)
      })
    })
  }